package com.larry.cleaner;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.larry.isn.LarryFileReader;
import com.larry.isn.LarryFileWriter;
import com.larry.util.LarryConst;
import com.larry.util.LarryUtil;

public class DataCleaner {

	public void clean() {
		try {
			List<String> newCacheDatas = this.getDatas();
			this.updateDataFile(newCacheDatas);
			this.removeFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<String> getDatas() {
		List<String> serialNrs = new ArrayList<String>();
		try {
			File folder = new File(LarryConst.CACHE_PATH);
			for (File file : folder.listFiles()) {
				serialNrs.add(file.getName().substring(0, file.getName().length() - 4));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return serialNrs;
	}

	private void removeFile() throws Exception {
		File folder = new File(LarryConst.CACHE_PATH);
		for (File file : folder.listFiles()) {
			file.delete();
		}
	}

	private void updateDataFile(List<String> cacheDatas) throws Exception {
		LarryFileReader reader = new LarryFileReader(LarryUtil.getSrcFile(LarryConst.DATA_FILE));
		try {
			List<String> datas = reader.read();

			Map<String, String> maps = new HashMap<String, String>();
			for (String data : datas) {
				maps.put(data, data);
			}
			for (String cacheData : cacheDatas) {
				if (maps.get(cacheData) != null) {
					maps.remove(cacheData);
				}
			}
			LarryFileWriter writer = new LarryFileWriter(LarryUtil.getSrcFile(LarryConst.DATA_FILE));
			writer.write(new ArrayList<String>(maps.keySet()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
